#ifndef __TCP_H__
#define __TCP_H__
#include "ip.h"
#include "pbuf.h"
#include "ip_addr.h"

struct tcp_pcb;


typedef void (*tcp_recv_fn)(void *arg, struct tcp_pcb *pcb, struct pbuf *p,
    ip_addr_t *addr, uint16_t port);


#define TCP_FLAGS 0x3fU

#define PACK_STRUCT_FIELD(x) x

#define TCPH_FLAGS(phdr)  (ntohs((phdr)->_hdrlen_rsvd_flags) & TCP_FLAGS)

#define TCPH_HDRLEN(phdr) (ntohs((phdr)->_hdrlen_rsvd_flags) >> 12)

#define TCPH_HDRLEN_SET(phdr, len) ((phdr)->_hdrlen_rsvd_flags = htons((uint16_t)(len) << 12))


#define TF_FLAGS_FIN   ((uint8_t)0x01U)   /*Reserver Not set  */
#define TF_FLAGS_SYN   ((uint8_t)0x02U)   /*Not Set  */
#define TF_FLAGS_RST   ((uint8_t)0x04U)   /*Congestion Window Reduce  */
#define TF_FLAGS_PSH   ((uint8_t)0x08U)   /* ECN  */
#define TF_FLAGS_ACK   ((uint8_t)0x10U)   /*  */
#define TF_FLAGS_URG   ((uint8_t)0x20U)   /*  */

#define TF_NODELAY     ((uint8_t)0x40U)   /*  */
#define TF_NAGLEMEMERR ((uint8_t)0x80U)   /*  */

#define TF_SMMP_ACK    ((uint8_t)TF_FLAGS_ACK|TF_FLAGS_PSH)


struct tcp_pcb{
	IP_PCB
	uint8_t flags;
	uint16_t local_port;
	uint16_t remote_port;
        uint32_t rcv_sqe;
 	uint32_t rcv_nxt;   
	uint16_t rcv_wnd;
        uint8_t  tcp_hdrlen;
        tcp_recv_fn recv;
	struct tcp_pcb *next;  	
};

typedef struct tcp_hdr {
  PACK_STRUCT_FIELD(uint16_t src);
  PACK_STRUCT_FIELD(uint16_t dest);
  PACK_STRUCT_FIELD(uint32_t seqno);
  PACK_STRUCT_FIELD(uint32_t ackno);
  PACK_STRUCT_FIELD(uint16_t _hdrlen_rsvd_flags);
  PACK_STRUCT_FIELD(uint16_t wnd);
  PACK_STRUCT_FIELD(uint16_t chksum);
  PACK_STRUCT_FIELD(uint16_t urgp);  
}Pack_tcp_hdr;

/*
***PCB分配内存
*/
struct tcp_pcb*
tcp_new(void);
/*
***PCB绑定配置
*/
uint8_t
tcp_bind(struct tcp_pcb *pcb,ip_addr_t *ipaddr,uint16_t port);
/*
***为PCB块注册读取数据回调函数
*/
void
tcp_recv(struct tcp_pcb *pcb,tcp_recv_fn recv);
#endif
